package com.ic.controller;

import com.ic.common.DroolsContainer;
import com.ic.domain.Rule;
import com.ic.service.RuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/rule")
public class RuleController {
    @Autowired
    private DroolsContainer droolsContainer;
    @Autowired
    private RuleService ruleService;

    @PostMapping
    public Rule addRule(@RequestBody Rule rule) {
        ruleService.save(rule);
        droolsContainer.checkAndUpdate(rule.getAppId());
        return rule;
    }

    @GetMapping
    public List<Rule> list() {
        return ruleService.list();
    }

    @PutMapping("/{id}")
    public Rule saveRule(@PathVariable("id") String id, @RequestBody Rule rule) {
        rule.setId(id);
        ruleService.save(rule);
        return rule;
    }

    @DeleteMapping("/{id}")
    public ResponseEntity delete(@PathVariable("id") String id) {
        ruleService.delete(id);
        droolsContainer.delete(id);
        return ResponseEntity.ok(id);
    }
}
